/* vim: set ts=2 et sw=2 cindent fo=qroca: */

package com.globant.google.mendoza.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globant.google.mendoza.MendozaServer;
import com.globant.google.mendoza.MendozaRequest;
import com.globant.google.mendoza.MendozaServerState;
import com.globant.google.mendoza.malbec.BuyerCoupon;

/** Represents the mendoza add coupon command.
 */
public final class MendozaAddCouponCommand extends MendozaBaseCommand {

  /** The class logger.
   */
  private static Log log = LogFactory.getLog(MendozaAddCouponCommand.class);

  /** The coupon code label. */
  private final String couponCodeLabel = "Coupon code";

  /** Creates an instance of MendozaLoginCommand.
   *
   * @param mendozaRequest The mendoza server request.
   *
   * @param mendoza The mendoza server.
   *
   * @param mendozaState The mendoza server state.
   */
  public MendozaAddCouponCommand(
      final MendozaRequest mendozaRequest, final MendozaServer mendoza,
      final MendozaServerState mendozaState) {
    super(mendozaRequest, mendoza, mendozaState);
    setName("Add coupon");
  }

  /** Executes the mendoza server add coupon command.
   */
  public void execute() {
    log.trace("Entering execute");
    MendozaCommandResult result = new MendozaCommandResult();
    String commandResultMsg =
        "OK - Add coupon command sent to the mendoza server.";
    try {
      setRequestParameters();
      result.setSuccess(commandResultMsg);
    } catch (RuntimeException e) {
      commandResultMsg = e.getMessage();
      result.setError(commandResultMsg);
    }
    setResult(result);
    logCommand(this);
    log.trace("Leaving execute");
  }

  /** Sets the login command parameters.
   */
  private void setRequestParameters() {
    log.trace("Entering setRequestParameters");
    String couponCode =
      getMendozaRequest().getRequestParameters().getProperty("code");
    if (couponCode == null) {
      log.trace("Leaving setRequestParameters");
      throw new RuntimeException("The coupon code cannot be null");
    }
    getMendozaState().addCoupon(new BuyerCoupon(couponCode));
    logRequestParameter(couponCodeLabel, couponCode);
    log.trace("Leaving setRequestParameters");
  }
}

